﻿using Cl.Model.Results;
using Cl.Utils.Helper;
using Cl.Utils;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cl.Repository;
using BaseShopEntity = Cl.Entity.DataBaseEntity.Shops.BaseShop;
using Cl.Model.DataBaseEntityDtos.Shops.BaseShop;
using Cl.Utils.Helper.AutoMap;
using NetTaste;
using Cl.Utils.Primitives.Const;
using Microsoft.AspNetCore.Mvc;
using Cl.Service.Service.System.UploadFile;

namespace Cl.Service.Service.Shops.BaseShop
{
    public class BaseShopService : IBaseShopService
    {

        private readonly ClRepository<BaseShopEntity> BaseShopRepository;
        private readonly IFileService FileService;
        public BaseShopService(ClRepository<BaseShopEntity> baseShopRepository, IFileService fileService)
        {
            BaseShopRepository = baseShopRepository;
            FileService = fileService;
        }

        public async Task<ResultInfoModel> Delete(List<int> ids)
        {
            if (ids == null || ids.Count <= 0)
                return GetResult.Error("参数不能为null");

            try
            {
                //数据准备
                var result = await BaseShopRepository.AsUpdateable(new BaseShopEntity() { DeletedId = GlobalUserManager.UserId, DeleteTime = DateTime.Now })
                    .UpdateColumns(it => new { it.DeletedId, it.DeleteTime })
                    .Where(x => ids.Contains(x.Id)).ExecuteCommandAsync();
                return GetResult.Success();
            }
            catch (Exception ex)
            {
                LoggerHelper.TryCatch(ex);
                return GetResult.Error(ex.Message);
            }
        }


        public async Task<PageResultModel<BaseShopOutputDto>> Query(SearchBaseShopDto request)
        {
            RefAsync<int> total = 0;
            var response = new PageResultModel<BaseShopOutputDto>
            {
                Result = new List<BaseShopOutputDto>()
            };

            var sql = BaseShopRepository.AsQueryable()
                .Includes(g => g.BaseGoodsList)
                .Includes(c => c.CreateUser)
                .Includes(up => up.UpdateUser);

            sql.OrderBy(p => p.CreateTime, OrderByType.Desc);
            // 计算开始和结束索引
            List<BaseShopEntity> list;
            if (request.IsPage)
            {
                list = await sql.ToPageListAsync(request.PageIndex, request.PageSize, total);
            }
            else
            {
                list = await sql.ToListAsync();
                total = list.Count;
            }

            response.TotalCount = total;
            response.Result = list.Select(x => new BaseShopOutputDto(x) { }).ToList();

            return response;


        }

        public async Task<BaseShopOutputDto?> FindShopData(int shopId)
        {
            BaseShopOutputDto? result = null;
            var obj = await BaseShopRepository.AsQueryable()
                .Where(x => x.Id == shopId)
                .Includes(gs => gs.BaseGoodsList)
                .Includes(gp => gp.GoodsGroupList).FirstAsync();
            if (obj != null)
                result = new BaseShopOutputDto(obj) { }; //obj.MapTo<BaseShopOutputDto, BaseShopEntity>();
            //AutoMapHelper.MapTo<BaseShopEntity, BaseShopOutputDto>(obj, result);
            return result;
        }

        public async Task<BaseShopOutputDto?> FindUserShopData(int userId)
        {
            userId = 1;
            BaseShopOutputDto? result = null;
            var obj = await BaseShopRepository.GetFirstAsync(x => x.UserId == userId);
            if (obj != null)
                result = obj.MapTo<BaseShopEntity, BaseShopOutputDto>();
            return result;
        }

        public async Task<ResultInfoModel> Save(BaseShopInputDto obj)
        {
            try
            {
                if (obj == null)
                    return GetResult.Error("参数不能null");

                //数据准备
                var operationData = obj.MapTo<BaseShopInputDto, BaseShopEntity>();
                operationData.CreateId = GlobalUserManager.UserId;
                operationData.CreateTime = DateTime.Now;
                operationData.AuditState = AuditStateConst.Approval;
                var result = await BaseShopRepository.AsInsertable(operationData).ExecuteReturnEntityAsync();
                if (result.Id != 0)
                    return GetResult.Success(result.Id.ToString());
                return GetResult.Error("操作失败");
            }
            catch (Exception ex)
            {
                LoggerHelper.TryCatch(ex);
                return GetResult.Error(ex.Message);
            }
        }


        public async Task<ResultInfoModel> Update(BaseShopInputDto obj)
        {
            try
            {
                if (obj == null)
                    return GetResult.Error("参数不能为null");
                if (obj.Id == 0)
                    return GetResult.Error("参数不能为null");

                //数据准备
                var operationData = obj.MapTo<BaseShopInputDto, BaseShopEntity>();
                operationData.UpdateId = GlobalUserManager.UserId;
                operationData.UpdateTime = DateTime.Now;
                operationData.AuditState = AuditStateConst.Approval;
                var result = await BaseShopRepository.AsUpdateable(operationData).IgnoreColumns(it => new { it.CreateTime, it.CreateId }).ExecuteCommandAsync();
                return GetResult.Success();
            }
            catch (Exception ex)
            {
                LoggerHelper.TryCatch(ex);
                return GetResult.Error(ex.Message);
            }
        }

        public async Task<ResultInfoModel> OpenOrCloseShop(int shopId, bool enable)
        {
            if (shopId == 0)
                return GetResult.Error("参数不能为null");

            //数据准备
            var operationData = new BaseShopEntity();
            operationData.Id = shopId;
            operationData.UpdateId = GlobalUserManager.UserId;
            operationData.UpdateTime = DateTime.Now;
            operationData.IsOpenBusiness = enable;
            var result = await BaseShopRepository.AsUpdateable(operationData)
                .UpdateColumns(it => new { it.UpdateId, it.UpdateTime, it.IsOpenBusiness }).ExecuteCommandAsync();
            return GetResult.Success();
        }

        public async Task<ResultInfoModel> FindShopHomeInfo(int shopId)
        {
            //const  count_order={
            //"id":5,
            //"shop_name":"测试"
            //,"today":[{"today_num_total":0,"today_money_total":null}]
            //,"yesterday":[{"yesterday_num_total":0,"yesterday_money_total":null}]
            //,"total":[{"all_num_total":1,"all_money_total":"188.00"}]}

            if (shopId == 0)
                return GetResult.Error("参数不能为null");

            var obj = await BaseShopRepository.GetByIdAsync(shopId);
            if (obj == null)
                return GetResult.Error("查询结果为null");
            var todayTotalNum = 1;
            var todayTotalMoney = 188.00;
            var yesterdayTotalNum = 0;
            var yesterdayTotalMoney = 0;
            var totalOrderCount = 1;
            var totalOrderMoney = 188.00;

            return GetResult.Success(string.Empty, new
            {
                obj.Id,
                obj.Title,
                obj.IsOpenBusiness,
                todayTotalNum,
                todayTotalMoney,
                yesterdayTotalNum,
                yesterdayTotalMoney,
                totalOrderCount,
                totalOrderMoney
            });
        }


        public async Task<ResultInfoModel> ApplyShopQualifications([FromForm] ShopQualificationInputDto obj)
        {

            if (obj == null || obj.UserId == 0)
                return GetResult.Error("参数不能为null");

            string shopId = string.Empty;
            var findShop = await BaseShopRepository.GetFirstAsync(x => x.UserId == obj.UserId);
            if (findShop == null)
            {
                var saveRes = await Save(new BaseShopInputDto()
                {
                    UserId = obj.UserId,
                    Title = obj.ShopName,
                });
                shopId = saveRes.Message;
            }
            else
            {
                findShop.AuditState = AuditStateConst.Approval;
                findShop.Title = obj.ShopName;
                await BaseShopRepository.AsUpdateable(findShop).UpdateColumns(it => new { it.AuditState, it.Title }).ExecuteCommandAsync();
                shopId = findShop.Id.ToString();
            }

            return GetResult.Success(string.Empty, shopId);
        }

        public async Task<ResultInfoModel> AuditShopQualifications([FromBody] ShopQualificationAuditDto obj)
        {
            if (obj == null || obj.ShopIds == null || obj.ShopIds.Count <= 0)
                return GetResult.Error("参数不能为null");
            var audit = await BaseShopRepository.AsUpdateable(new BaseShopEntity()
            {
                AuditRemark = string.IsNullOrEmpty(obj.AuditRemark) ? "无" : obj.AuditRemark,
                AuditState = obj.AuditResult,
            }).UpdateColumns(it => new { it.AuditState, it.AuditRemark })
            .Where(x => obj.ShopIds.Contains(x.Id))
            .ExecuteCommandAsync();

            return GetResult.Success();

        }

        public async Task<ResultInfoModel> UploadShopQualificationFile([FromForm] ShopQualificationInputDto obj)
        {

            if (obj == null || obj.ShopId == 0)
                return GetResult.Error("参数不能为null");
            string IDCardReversePath = string.Empty;
            if (obj.IDCardReverse != null)
            {
                var upResult = await FileService.UploadFileAsync(obj.IDCardReverse, Utils.Primitives.Class.UploadFile.UploadType.IDCardReverse, obj.ShopId.ToString());
                if (upResult.IsSuccess)
                    IDCardReversePath = upResult.Message;
            }

            string IDCardFrontPath = string.Empty;
            if (obj.IDCardFront != null)
            {
                var upResult = await FileService.UploadFileAsync(obj.IDCardFront, Utils.Primitives.Class.UploadFile.UploadType.IDCardFront, obj.ShopId.ToString());
                if (upResult.IsSuccess)
                    IDCardFrontPath = upResult.Message;
            }

            string BusinessLicensePath = string.Empty;
            if (obj.BusinessLicense != null)
            {
                var upResult = await FileService.UploadFileAsync(obj.BusinessLicense, Utils.Primitives.Class.UploadFile.UploadType.BusinessLicense, obj.ShopId.ToString());
                if (upResult.IsSuccess)
                    BusinessLicensePath = upResult.Message;
            }

            return GetResult.Success();
        }
    }
}
